package io.github.jesse205.dragdrop.pro.view

import android.content.Context
import android.util.AttributeSet
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.appcompat.widget.SwitchCompat
import io.github.jesse205.dragdrop.pro.R

/**
 * 开关布局，使用主题中的按钮，适配MD2和MD3
 * */
class SwitchLayout : FrameLayout {
    private val switchView: SwitchCompat

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(
        context,
        attrs,
        R.attr.switchLayoutStyle
    )

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : this(
        context,
        attrs,
        defStyleAttr, 0
    )

    constructor(
        context: Context,
        attrs: AttributeSet?,
        defStyleAttr: Int,
        defStyleRes: Int
    ) : super(context, null, 0, defStyleRes) {
        val a = context.obtainStyledAttributes(
            attrs, R.styleable.SwitchLayout, defStyleAttr, 0
        )

        val name =
            a.getString(R.styleable.SwitchLayout_android_name) ?: SwitchCompat::class.java.name

        @Suppress("UNCHECKED_CAST")
        val clazz = Class.forName(name) as Class<SwitchCompat>
        val constructor =
            clazz.getConstructor(Context::class.java, AttributeSet::class.java)

        switchView = constructor.newInstance(context, attrs)

        addView(
            switchView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
        )
        a.recycle()
    }

}